import Progress from './assert/js/progress';
import ThreePresenter from './assert/js/my_three'
//取消所有log输出

import data_show from './data_show';

function getReqParam() {
    const query = window.location.search.substring(1);
    let res = {}
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        res[pair[0]] = pair[1]
    }
    return res
}



function setBuildingName(bName) {
    $('.build_name').html(bName)
}
const progress = new Progress($('#date-progress'), 8, 16, $('.slide-time span'))
progress.init()


const presenter = new ThreePresenter(8, 16)
const debug = false


if (!debug) {
    console.log = () => { }
}
const getDaeUrl = (dae, prefix) => `https://${prefix}/dae/${dae}.dae`

let loadUrl = []
function getBuildingData() {
    const qs = getReqParam()
    let colorUrl
    let splits = qs.dae.trim().split(',')
    let prefix = qs.prefix.trim()
    if (splits.length == 1) {
        //只有一个楼栋
        loadUrl = getDaeUrl(splits[0], prefix)
    } else {
        loadUrl = splits.map(function (s) {
            const [t, u] = s.split('-')
            return {
                t: decodeURI(t),
                u: getDaeUrl(u, prefix)
            }
        }
        )
    }


    if (debug) {
        loadUrl = [
            { t: '南区', u: `assert/dae/噪声没路的模型.dae` },
            { t: '北区', u: `assert/dae/噪声没路的模型.dae` }
        ]
        loadUrl = `assert/dae/噪声没路的模型.dae`
        colorUrl = `assert/json/噪声没路的模型.json`
    } else {
        console.log = () => { }
        colorUrl = `${qs.url.trim()}?code=${qs.code.trim()}`
    }
    //设置内部数据
    setBuildingName(decodeURI(qs.building.trim()))

    //是否显示冬至
    if (qs.winter == 'false') {
        $($('.session-box span')[1]).hide()
    }
    //根据模型数，显示ui
    const $daes = $('#daes')
    let url
    $('#loading_mask').show()
    if (loadUrl instanceof Array) {
        $daes.show()
        //加载动画  
        url = loadUrl[0].u
        loadUrl.forEach(({ t }) => {
            $daes.append(`<span>${t}</span>`)
        })

    } else {
        url = loadUrl
        $daes.hide()
    }
    const [lng, lat] = qs.lnglat.trim().split(",")
    presenter.init(url, colorUrl, '大寒', () => {
        $('#sunshine').css('display', 'flex')
        $('#loading_mask').hide()
        initDate()
    }, debug, lng, lat)


}
getBuildingData()



//进度条改变回调（此时需要停止自动播放）
//注意，该回调仅仅当需要更新建模时才会触发
//即建模动画刷新触发的progress change并不会触发此回调
progress.onChangeCall = (h, m) => {
    // console.log("onChangeCall", h, m)
    //暂停图标
    progress.stopPlayerIcon()

    let cur = presenter.lastDate
    let d = new Date(cur.getFullYear(), cur.getMonth(), cur.getDate(), h, m)
    presenter.renderAtTime(d)
}

//改变图标颜色，无副作用回调
// progress.onChangePur = (n) => {
//     for(let btn of $('.abs_btn')){
//         $(btn).css('filter', `brightness(${Math.abs(n / 100 - 0.5)  * 2})`)
//     }
// }

// 播放逻辑
{

    $('.progress-wrap .player').on('click', function () {
        if ($('.progress-wrap .player img').attr('src').indexOf('play') != -1) {
            //开始播放
            progress.startPlayerIcon()
            presenter.renderPlayer(presenter.lastDate, 1200, (cell) => {
                //第二个参数：false。表示progress的改变不会再触发建模更新
                progress.change(cell, false)
            })
        } else {
            progress.stopPlayerIcon()
            //不能停止帧动画
            presenter.stopRenderPlayer()
        }
    })
}
function setAtTime(date) {
    presenter.renderAtTime(date)
    //不需要回调到模型
    // console.log(date.getMinutes(), Math.floor(date.getMinutes() / progress.cell))
    let v
    if (date.getHours() >= presenter.end) {
        v = presenter.end * 6
    } else if (date.getHours() <= presenter.start) {
        v = presenter.start * 6
    } else {
        v = date.getHours() * 6 + Math.floor(date.getMinutes() / progress.cell)
    }
    progress.change(v, false)
}
// setAtTime(new Date())

//冬至：8~16 12.21
//大寒：8~16 1.20
//春分：8~16 3.20
//夏至：7~18 6.21
function getTerms(ses) {
    return [
        //注意：js的 Date month 是从0开始的， 所以节气月份都要-1
        new Date(2021, 11, 21, ses[0][0], ses[0][1]), //冬至
        new Date(2022, 0, 20, ses[1][0], ses[1][1]),
        new Date(2022, 2, 20, ses[2][0], ses[2][1]),
        new Date(2022, 5, 21, ses[3][0], ses[3][1])
    ]
}
//暂时都以8点开始
const ses = [
    [8, 16], [8, 16], [8, 16], [7, 18]
]
let terms = getTerms(ses)

//根据当前日期获取节气时间
function getUseHM(termDate, date, se) {
    if (date == null) {
        //简化使用
        date = new Date()
    }
    let h = date.getHours()
    let m = date.getMinutes()
    if (h < se[0]) {
        h = se[0]
        m = 0
    }

    if (h > se[1]) {
        h = se[1]
        m = 0
    }
    return new Date(termDate.getFullYear(), termDate.getMonth(), termDate.getDate(), h, m)
}

let currentIdx = 0
let startIdx = 0

function initDate() {
    //切换到当前节气, 根据用户当前时、分 跳到对应节气的时、分
    $($('.session-box span')[currentIdx]).attr('class', '')

    currentIdx = 0 //默认冬至
    
    $($('.session-box span')[currentIdx]).attr('class', 'select')
    //渲染对应日期
    let se = ses[currentIdx]
    let cur = terms[currentIdx]
    // let t = getUseHM(terms[currentIdx], new Date(), se)
    let t = new Date(cur.getFullYear(), cur.getMonth(), cur.getDate(), 12)
    // console.log("month", t.getMonth())
    presenter.renderAtTime(t)
    //进度条跳转, false，不进一步出发presenter
    //可能改变起始和结束时间
    progress.changeDate(t, false, false, se)

}

//节气切换逻辑
$('.session-box span').on('click', function () {
    let index = $(this).index()
    //0冬至 1大寒 2春秋分 3夏至
    ///修改：0 大寒，1冬至
    $($('.session-box span')[currentIdx]).attr('class', '')
    currentIdx = index
    $(this).attr('class', 'select')
    //保存上次的时、分
    //todo [8, 16]
    // console.log(presenter.lastDate)
    let t = getUseHM(terms[currentIdx], presenter.lastDate, ses[currentIdx])
    //此时会结束动画，但进度条还要改变
    // console.log("month", t.getMonth())
    presenter.changeSE(...ses[currentIdx])
    console.log("main index", index)
    presenter.renderAtTime(t)
    progress.changeSE(...ses[currentIdx])

    // if(currentIdx == 3){
    //     progress.changeSE(...ses[currentIdx])
    // }else{
    progress.changeDate(t, false, true, ses[currentIdx])
    // }

    presenter.changeTerm($(this).html())

})


//------------------模型切换----------------------


$('#daes span').on('click', function () {
    $(this).attr('class', 'select')
    $($('#daes span')[($(this).index() + 1) % 2]).attr('class', '')
    $('#loading_mask').show()

    //切换显示
    presenter.changeDaeLoad(loadUrl[$(this).index()].u)
    presenter.reset()
})
//默认选中第一个
$($('#daes span')[0]).attr('class', 'select')
//--------------------end-----------------




//免责通知
$('.no_man_notice').on('click', function () {
    $('#exemption_dialog').css({ bottom: 0 })
    $('#exemption_dialog .dialog-content').scrollTop(0)
})
$('canvas').on('click', function () {
    if ($('#exemption_dialog').css('bottom') === '0px') {
        $('#exemption_dialog').css({ bottom: '-80%' })
    }
})
$('.dialog-close').on('click', () => {
    $('#exemption_dialog').css({ bottom: '-80%' })

})

//重置按钮
$('#btn_reset').on('click', () => {
    presenter.reset()
})




data_show()